package com.labot.webapp.action;

import java.util.HashMap;
import java.util.Map;

import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.labot.model.User;
import com.labot.types.AuditType;
import com.labot.types.LoginType;
import com.labot.types.MailType;
import com.labot.util.StackTraceUtils;
import com.labot.util.StringUtils;
import com.labot.webapp.action.messages.TextMessagesType;

/**
 * @author Ing Enrique Barbeito.
 * 
 */
public class ResetPasswordAction extends BaseAction {
    private static final long serialVersionUID = -4037514607101222025L;
    private String username;


	public String form() {
    	return INPUT;
    }

    /**
     * Execute sending the password hint via e-mail.
     *
     * @return success if username works, input if not
     */
    public String reset() {
    	LoginType type = null;
    	Boolean error = false;

    	if (username == null || username.trim().equals("")) {
    		error = true;
			addActionError(super.getText(TextMessagesType.RESET_PASSWORD_ERROR_USERNAME.getKey()));
    	}
    	if (error) {
    		return INPUT;
    	}
    	//Crear clave nueva
    	User usr = null;
    	try {
    		usr = userManager.getUserByUsername(username);
    	} catch (UsernameNotFoundException e) {
    		log.info("Error al blanquear password a " + username + " (" + type + ")");
    		super.addActionError(super.getText(TextMessagesType.RESET_PASSWORD_USERNAME_NOT_FOUND.getKey()) + " " + username);
    		return INPUT;
    	}
    	
		String password = StringUtils.generarRandomInteger(6);
		log.info("Nueva clave para " + username + " (" + type + ") es: " +password);
		
		try {
			//Mail
			Map<String, String> props = new HashMap<String, String>();
			props.put("clave", password);
			mailEngine.sendMail(MailType.RESET_PASSWORD, usr.getEmail(), usr, props, null, super.getLocale());
			
			usr.setPassword(password);
			userManager.saveUser(usr, true);
			super.log(AuditType.INFO, "Password Reset to: " + usr.getUsername() + " <" + usr.getEmail() + ">");

		} catch (Exception e) {
			log.error(StackTraceUtils.getStackTrace(e));
			super.addActionError(super.getText(TextMessagesType.RESET_PASSWORD_USERNAME_NOT_FOUND.getKey()) + " " + username);
    		return INPUT;
		}
		addActionMessage(super.getText(TextMessagesType.RESET_PASSWORD_NEW_USERNAME.getKey()) + " " + username);
	
    	
    	
    	return SUCCESS;
    }
    
    public void setUsername(String username) {
        this.username = username;
    }
    
    public String getUsername() {
		return username;
	}


}
